import UserModel, { IUser } from '../models/UserModel';
import jwt from 'jsonwebtoken';
import config from '@/config/config.default';
class UserService {
  // 用户注册
  public async createUser(params: IUser) {
    try {
      const user = await UserModel.create(params);
      return user;
    } catch (error) {
      console.error(error);
      throw error;
    }
  }

  /** TODO 用户登录 */
  public async userLogin(params: { username: string; password: string }) {
    try {
      const user = await UserModel.findOne({ username: params.username });
      if (!user) {
        return {
          code: 401,
          message: '账号错误',
        };
      } else if (user?.password && user.password !== params.password) {
        return {
          code: 401,
          message: '密码错误',
        };
      } else {
        const token = jwt.sign(
          { username: params.username },
          config.tokenSecrets,
          { expiresIn: '60s' }, // expiresIn 单位s m/min/minutes h/hr/hours d/days
        );
        return {
          code: 200,
          token,
        };
      }
    } catch (error) {
      console.error(error);
      throw error;
    }
  }

  /** TODO 注销 */
  /** TODO 用户信息管理 */

  // 获取用户信息
  public async getUserById(id: string) {
    try {
      const user = await UserModel.findById(id).select(['username', 'email']);
      return user;
    } catch (error) {
      console.error(error);
      throw error;
    }
  }
}

export default new UserService();
